package com.v9.common.utils.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;

/**
 * 文件处理工具类
 *
 * @author ruoyi
 */
public class FileUtils {
    private static final HashMap<String, String> mFileTypes = new HashMap<String, String>();

    static {
        FileTypeEnum[] values = FileTypeEnum.values();
        for (FileTypeEnum type : values) {
            mFileTypes.put(type.name(), type.getValue());
        }
    }

    public static String getFileType(String filePath) {
        return mFileTypes.get(getFileHeader(filePath));
    }

    public static String getFileType(byte[] file) {
        String fileHeader = getFileHeader(file);
        for(String key:mFileTypes.keySet()){
            if(fileHeader.startsWith(mFileTypes.get(key))){
                return key;
            }
        }
        return mFileTypes.get(fileHeader);
    }

    private static String getFileHeader(String filePath) {
        File file = new File(filePath);
        if (!file.exists() || file.length() < 11) {
            return "null";
        }
        FileInputStream is = null;
        String value = null;
        try {
            is = new FileInputStream(file);
            byte[] b = new byte[10];
            is.read(b, 0, b.length);
            value = bytesToHexString(b);
        } catch (Exception e) {
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
        return value;
    }

    private static String getFileHeader(byte[] file) {
        byte[] b = new byte[32];
        for (int i = 0; i < b.length; i++) {
            b[i] = file[i];
        }
        return bytesToHexString(b);
    }

    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length == 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

}
